<template>
    <div class="login">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
<!--            <h3 class="title">电工电子理实一体化学校管理系统</h3>-->
          <h3 class="title">{{ $locale('login.title') }}</h3>
            <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" auto-complete="off" :placeholder="$locale('register.account number')">
                    <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" auto-complete="off" :placeholder="$locale('student.add.password')" @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
                </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
                <el-input v-model="loginForm.code" auto-complete="off" :placeholder="$locale('register.Verification code')" style="width: 63%" @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                </el-input>
                <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">{{ $locale('login.remember password') }}</el-checkbox>
            <span class="forget" @click="open = true">{{ $locale('login.forgot password') }}</span>
            <el-form-item style="width: 100%">
                <el-button :loading="loading" size="medium" type="primary" style="width: 100%" @click.native.prevent="handleLogin">
                    <span v-if="!loading">{{ $locale('login.Sign in') }}</span>
                    <span v-else>{{$locale('login.Logging in ..')}}</span>
                </el-button>
                <div style="float: right" v-if="register">
                    <router-link class="link-type" :to="'/register'">{{ $locale('login.Register Now') }}</router-link>
                </div>
            </el-form-item>
        </el-form>
        <el-dialog :title="$locale('school.add.Password Reset')" :visible.sync="open" width="500px">
            <el-form :model="form" ref="form" size="small" label-width="100px" :rules="rules">
                <el-form-item :label="$locale('student.add.user name')" prop="userName">
                    <el-input v-model="form.userName" :placeholder="$locale('jobList.add.Please enter your email address')" />
                </el-form-item>
                <el-form-item :label="$locale('jobList.add.email')" prop="mailAddress">
                    <el-input v-model="form.mailAddress" :placeholder="$locale('jobList.add.Please enter your email address')" />
                </el-form-item>
                <el-form-item :label="$locale('login.Email verification code')" prop="code">
                    <el-input v-model="form.code" :placeholder="$locale('login.Please enter the email verification code')" />
                    <el-input :placeholder="$locale('login.Please enter the email verification code')" v-model="form.code">
                        <el-button slot="append" @click="getEmailCode">{{ $locale('login.Obtain verification code') }}</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item :label="$locale('myClass.add.Login password')" prop="oldPassword">
                    <el-input v-model="loginForm.oldPassword" :placeholder="$locale('school.add.Set a login password of 6 to 20 digits')" />
                </el-form-item>
                <el-form-item :label="$locale('school.add.Confirm password')" prop="password">
                    <el-input v-model="loginForm.password" :placeholder="$locale('classList.Please enter your login password again')" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ $locale('school.add.Submit') }}</el-button>
                <el-button @click="open = false">{{$locale('classList.add.Cancel')}}</el-button>
            </div>
        </el-dialog>
        <!--  底部  -->
        <div class="el-login-footer">
            <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>
        </div>
    </div>
</template>

<script>
import { getCodeImg, emailcode, resetPwd } from '@/api/login';
import Cookies from 'js-cookie';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import { getSchoolByLogin } from '@/api/business/school';

export default {
    name: 'Login',
    data() {
        return {
            codeUrl: '1',
            loginForm: {
                username: '',
                password: '',
                // username: 'zhongnandaxue',
                // password: '123456',
                rememberMe: false,
                code: '',
                uuid: ''
            },
            loginRules: {
                username: [{ required: true, trigger: 'blur', message: this.$locale('register.Please enter your account') }],
                password: [{ required: true, trigger: 'blur', message: this.$locale('register.Please enter your password') }],
                code: [{ required: true, trigger: 'change', message: this.$locale('register.Please enter the verification code') }]
            },
            loading: false,
            // 验证码开关
            captchaEnabled: true,
            // 注册开关
            register: false,
            redirect: undefined,
            open: false,
            form: {
                userName: '',
                mailAddress: '',
                code: '',
                oldPassword: '',
                password: ''
            },
            // 表单校验
            rules: {
                userName: [{ required: true, trigger: 'blur', message: this.$locale('register.Please enter your account') }],
                mailAddress: [{ required: true, message: this.$locale('jobList.add.Please enter your email address'), trigger: 'blur' }],
                code: [{ required: true, message: this.$locale('login.Please enter the email verification code'), trigger: 'blur' }],
                oldPassword: [
                    { required: true, message: this.$locale('classList.Please enter your login password'), trigger: 'blur' },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' }
                ],
                password: [
                    { required: true, message: this.$locale('classList.Please enter your login password again'), trigger: 'blur' },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' },
                    { validator: this.validatePasswordConfirm, trigger: 'blur' }
                ]
            }
        };
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect;
            },
            immediate: true
        }
    },
    created() {
        this.getCode();
        this.getCookie();
    },
    methods: {
        validatePasswordConfirm(rule, value, callback) {
            if (value === '') {
                callback(new Error(this.$locale('classList.Please enter your login password again')));
            } else if (value !== this.loginForm.password) {
                callback(new Error(this.$locale('classList.Entered passwords differ')));
            } else {
                callback();
            }
        },
        getEmailCode() {
            emailcode({
                userName: this.form.userName,
                mailAddress: form.mailAddress
            }).then((res) => {
                if (res.code == 200) this.$modal.msgSuccess(this.$locale('login.Successfully obtained'));
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    resetPwd(this.form).then((response) => {
                        this.$modal.msgSuccess(this.$locale('geWudevice.add.tip5'));
                        this.handleQuery();
                        this.open = false;
                    });
                }
            });
        },
        getCode() {
            getCodeImg().then((res) => {
                this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
                if (this.captchaEnabled) {
                    this.codeUrl = 'data:image/gif;base64,' + res.img;
                    this.loginForm.uuid = res.uuid;
                }
            });
        },
        getCookie() {
            const username = Cookies.get('username');
            const password = Cookies.get('password');
            const rememberMe = Cookies.get('rememberMe');
            this.loginForm = {
                username: username === undefined ? this.loginForm.username : username,
                password: password === undefined ? this.loginForm.password : decrypt(password),
                rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
            };
        },
        getSchoolByLoginFc() {
            getSchoolByLogin().then(({ data }) => {
                this.schoolData = data;
                const currentDate = new Date();
                const targetDateTime = new Date(data.lifespan);

                const timeDiff = targetDateTime.getTime() - currentDate.getTime();
                const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
                if (daysDiff <= 30) {
                    this.$alert(`距离到期还有 ${daysDiff} 天,到期时间为：${data.lifespan}`, data.schoolName + '到期时间提醒！', {
                        dangerouslyUseHTMLString: true
                    });
                }
            });
        },
        handleLogin() {
            if (this.loginForm.username == 'admin') {
                this.$alert('学校端禁止登录admin账号');
                return;
            }
            this.$refs.loginForm.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    if (this.loginForm.rememberMe) {
                        Cookies.set('username', this.loginForm.username, { expires: 30 });
                        Cookies.set('password', encrypt(this.loginForm.password), {
                            expires: 30
                        });
                        Cookies.set('rememberMe', this.loginForm.rememberMe, {
                            expires: 30
                        });
                    } else {
                        Cookies.remove('username');
                        Cookies.remove('password');
                        Cookies.remove('rememberMe');
                    }
                    this.$store
                        .dispatch('Login', this.loginForm)
                        .then(() => {
                            this.$router.push({ path: this.redirect || '/' }).catch(() => {});
                            this.getSchoolByLoginFc();
                        })
                        .catch(() => {
                            this.loading = false;
                            if (this.captchaEnabled) {
                                this.getCode();
                            }
                        });
                }
            });
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.forget {
    color: #606266;
    font-size: 14px;
    float: right;
    cursor: pointer;
}
.login {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 100%;
    background-image: url('../assets/images/login-background1.png');
    background-size: cover;
    padding-right: 15%;
}
.title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
}

.login-form {
    border-radius: 6px;
    // background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
    .el-input {
        height: 38px;
        input {
            height: 38px;
        }
    }
    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
    }
}
.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}
.login-code {
    width: 33%;
    height: 38px;
    float: right;
    img {
        cursor: pointer;
        vertical-align: middle;
    }
}
.el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}
.login-code-img {
    height: 38px;
}
</style>
